package com.ultrapower.ctool.xn_app;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.base.RefreshParams;
import com.ultrapower.ctool.base.adapter.AbsCommonAdapter;
import com.ultrapower.ctool.base.adapter.AbsViewHolder;
import com.ultrapower.ctool.bean.Page;
import com.ultrapower.ctool.bean.TableModel;
import com.ultrapower.ctool.bean.TotalRowsPair;
import com.ultrapower.ctool.bean.WangGeBean;
import com.ultrapower.ctool.bean.XcxmBean;
import com.ultrapower.ctool.bean.XunChaBean;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.utils.InstanceUtil;
import com.ultrapower.ctool.utils.WeakHandler;
import com.ultrapower.ctool.widget.SyncHorizontalScrollView;
import com.ultrapower.ctool.widget.pullrefresh.AbPullToRefreshView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class XunChaResultActivity extends BaseActivity implements View.OnClickListener {

    private SparseArray<TextView> mTitleTvArray;
    private TextView xc_result_add;
    //表格部分
    private TextView tv_table_title_left;
    private LinearLayout right_title_container;
    private ListView leftListView;
    private ListView rightListView;
    private AbsCommonAdapter<TableModel> mLeftAdapter, mRightAdapter;
    private AbPullToRefreshView pulltorefreshview;
    private SyncHorizontalScrollView titleHorScv;
    private SyncHorizontalScrollView contentHorScv;
    private String identification;
    private Context mContext;
    private CustomApplication application;
    private WeakHandler mHandler = new WeakHandler();
    private int pageNo = 0;
    private String query_cid;
    private Page page = new Page().setPerPageSize(10);
    private Gson gson = new Gson();
    private ProgressDialog progressDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bd = msg.getData();
                    setData();
                    break;
                case 0:

                    Toast.makeText(getApplicationContext(), "系统加载错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xun_cha_result);
        application = (CustomApplication) getApplication();
        init();
    }

    public void init() {
        mContext = getApplicationContext();
        findByid();
        setListener();
        setData();
    }

    public void findByid() {
        pulltorefreshview = (AbPullToRefreshView) findViewById(R.id.pulltorefreshview_xc_result);
        tv_table_title_left = (TextView) findViewById(R.id.tv_table_title_left_xc_result);
        tv_table_title_left.setText("编号");
        leftListView = (ListView) findViewById(R.id.left_container_listview_xc_result);
        rightListView = (ListView) findViewById(R.id.right_container_listview_xc_result);
        right_title_container = (LinearLayout) findViewById(R.id.right_title_container_xc_result);
        getLayoutInflater().inflate(R.layout.table_right_title_xc_result, right_title_container);
        titleHorScv = (SyncHorizontalScrollView) findViewById(R.id.title_horsv_xc_result);
        contentHorScv = (SyncHorizontalScrollView) findViewById(R.id.content_horsv_xc_result);
        // 设置两个水平控件的联动
        titleHorScv.setScrollView(contentHorScv);
        contentHorScv.setScrollView(titleHorScv);
        xc_result_add = (TextView) findViewById(R.id.xc_result_add);
        xc_result_add.setOnClickListener(this);
        findTitleTextViewIds();
        initTableView();
    }

    /**
     * 初始化标题的TextView的item引用
     */
    private void findTitleTextViewIds() {
        mTitleTvArray = new SparseArray<>();
        for (int i = 0; i <= 20; i++) {
            try {
                Field field = R.id.class.getField("tv_table_title_" + 0);
                int key = field.getInt(new R.id());
                TextView textView = (TextView) findViewById(key);
                mTitleTvArray.put(key, textView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void initTableView() {
        mLeftAdapter = new AbsCommonAdapter<TableModel>(mContext, R.layout.table_left_item) {
            @Override
            public void convert(AbsViewHolder helper, TableModel item, int pos) {
                TextView tv_table_content_left = helper.getView(R.id.tv_table_content_item_left);
                tv_table_content_left.setText(item.getLeftTitle());
            }
        };
        mRightAdapter = new AbsCommonAdapter<TableModel>(mContext, R.layout.table_right_item) {
            @Override
            public void convert(AbsViewHolder helper, TableModel item, int pos) {
                TextView tv_table_content_right_item0 = helper.getView(R.id.tv_table_content_right_item0);
                TextView tv_table_content_right_item1 = helper.getView(R.id.tv_table_content_right_item1);
                TextView tv_table_content_right_item2 = helper.getView(R.id.tv_table_content_right_item2);

                tv_table_content_right_item0.setText(item.getText0());
                tv_table_content_right_item1.setText(item.getText1());
                tv_table_content_right_item2.setText(item.getText2());

                for (int i = 0; i < 16; i++) {
                    View view = ((LinearLayout) helper.getConvertView()).getChildAt(i);
                    if (i < 3) {
                        view.setVisibility(View.VISIBLE);
                    } else {
                        view.setVisibility(View.GONE);
                    }
                }
            }
        };
        leftListView.setAdapter(mLeftAdapter);
        rightListView.setAdapter(mRightAdapter);
    }

    public void setListener() {
        pulltorefreshview.setOnHeaderRefreshListener(new AbPullToRefreshView.OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(AbPullToRefreshView view) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo = 0;
                        doGetDatas(0, RefreshParams.REFRESH_DATA);
                    }
                }, 1000);
            }
        });
        pulltorefreshview.setOnFooterLoadListener(new AbPullToRefreshView.OnFooterLoadListener() {
            @Override
            public void onFooterLoad(AbPullToRefreshView view) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        doGetDatas(pageNo, RefreshParams.LOAD_DATA);
                    }
                }, 1000);
            }

        });
        leftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TableModel model = mLeftAdapter.getDatas().get(position);
                Intent intent = new Intent();
                intent.setClass(XunChaResultActivity.this, XunChaResultInfoActivity.class);
                model.getLeftTitle();
                intent.putExtra("remId", model.getLeftTitle());
                intent.putExtra("identification", identification);
                XunChaResultActivity.this.startActivity(intent);


            }
        });
    }

    public void setData() {
        doGetDatas(0, RefreshParams.REFRESH_DATA);
    }

    //网络请求
    public void doGetDatas(final int pageno, final int state) {
        final List<XcxmBean> wanggeBeanList = new ArrayList<XcxmBean>();
        Intent intent = getIntent();
        //System.out.println(intent.getStringExtra("query_cid"));
        query_cid = intent.getStringExtra("query_cid");
        identification = intent.getStringExtra("identification");
        showProgressDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    if (page.getTotalPageNum() >= (pageno + 1)) {

                        FormBody.Builder builder = new FormBody.Builder()
                                .add("page", "" + (pageno + 1))
                                .add("rows", "" + page.getPerPageSize())
                                .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                                .add("query_cid", query_cid);
                        RequestBody requestBody = builder.build();
                        //query_sid=1000012
                        Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "grid/query/c_aj_xcxm").post(requestBody).build();
                        Response response = client.newCall(request).execute();
                        if (response.isSuccessful()) {//成功
                            String result = response.body().string();
                            System.out.println(request);
                            TotalRowsPair<LinkedTreeMap> totalRowsPair = gson.fromJson(result, TotalRowsPair.class);
                            for (LinkedTreeMap row : totalRowsPair.getRows()) {
                                wanggeBeanList.add((XcxmBean) InstanceUtil.mapToObject(row, XcxmBean.class));
                            }
                            page.setTotalPageNum(totalRowsPair.getTotal());
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (state == RefreshParams.REFRESH_DATA) {
                                pulltorefreshview.onHeaderRefreshFinish();
                            } else {
                                pulltorefreshview.onFooterLoadFinish();
                            }
                            setDatas(wanggeBeanList, state);
                        }
                    });
                    closeProgressDialog();
                } catch (Exception e) {
                    closeProgressDialog();
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (state == RefreshParams.REFRESH_DATA) {
                                pulltorefreshview.onHeaderRefreshFinish();

                            } else {
                                pulltorefreshview.onFooterLoadFinish();
                            }
                            setDatas(wanggeBeanList, state);
                        }
                    });

                }
            }
        }).start();
    }

    private void setDatas(List<XcxmBean> wanggeBeanList, int type) {
        System.out.println(wanggeBeanList);
        if (wanggeBeanList.size() > 0) {
            List<TableModel> mDatas = new ArrayList<>();
            for (int i = 0; i < wanggeBeanList.size(); i++) {
                XcxmBean xcxmBean = wanggeBeanList.get(i);
                TableModel tableMode = new TableModel();
                tableMode.setLeftTitle(xcxmBean.getMid() + "");
                tableMode.setText0(xcxmBean.getCid() + "");
                tableMode.setText1(xcxmBean.getMname() + "");
                tableMode.setText2(xcxmBean.getItemvalue() + "");
                mDatas.add(tableMode);
            }
            boolean isMore;
            if (type == RefreshParams.LOAD_DATA) {
                isMore = true;
            } else {
                isMore = false;
            }
            mLeftAdapter.addData(mDatas, isMore);
            mRightAdapter.addData(mDatas, isMore);
            //加载数据成功，增加页数
            pageNo++;
//            if (mDatas.size() < 20) {
//                pulltorefreshview.setLoadMoreEnable(false);
//            }
            mDatas.clear();
        } else {
            //数据为null
            if (type == RefreshParams.REFRESH_DATA) {
                mLeftAdapter.clearData(true);
                mRightAdapter.clearData(true);
                //显示数据为空的视图
                //                mEmpty.setShowErrorAndPic(getString(R.string.empty_null), 0);
            } else if (type == RefreshParams.LOAD_DATA) {
                Toast.makeText(mContext, "没有最新数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(XunChaResultActivity.this);
            progressDialog.setMessage("正在加载，请稍等...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.xc_result_add:
                if ((identification != null && "rcxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目新增"))
                        || (identification != null && "zxxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目新增"))
                        ) {
                    Intent intent = new Intent(XunChaResultActivity.this, AddXunChaResultActivity.class);
                    intent.putExtra("cid", query_cid);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplication(), "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }
}
